package com.we.connect.weconnect.utils;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import com.we.connect.weconnect.model.remind.vo.RemindInfoVo;
import com.we.connect.weconnect.model.system.SysInfo;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.stereotype.Component;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

@Component
public class SendMsg {
    private static CloseableHttpClient httpClient;
    private static HttpPost httpPost;//用于提交登陆数据
    private static HttpGet httpGet;//用于获得登录后的页面

    public static final String CONTENT_TYPE = "Content-Type";

    private static Gson gson = new Gson();


    public static String sendMessage(SysInfo sysInfo, String toUser, RemindInfoVo remindInfoVo) throws IOException{
        // 获取发送Token
        String token = getToken(sysInfo.getCorpId(),sysInfo.getSecret());

        // 解析创建消息发送文本
        String postData = createPostData(toUser, Integer.parseInt(sysInfo.getAgentId()), remindInfoVo);

        // 发送消息
        String response = post("utf-8", CONTENT_TYPE,
                "https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=", postData, token);

        return response;
    }

    private static String createPostData(String toUser, int agentId, RemindInfoVo remindInfoVo) {
        Map<String,Object> weChatData = new HashMap<>();
        // 添加基础信息
        weChatData.put("touser", toUser);
        weChatData.put("agentid", agentId);
        weChatData.put("msgtype", remindInfoVo.getType());

        // 先对内容进行解析
        String content;
        try {
            content = ParseContentUtils.parseContent(remindInfoVo.getContent());
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        // 添加消息内容
        if(remindInfoVo.getType().equals("text")){
            Map<Object, Object> contentMap = new HashMap<>();
            contentMap.put("content", remindInfoVo.getTitle() + "\n------------------------------\n" + content);
            weChatData.put("text", contentMap);
        } else if (remindInfoVo.getType().equals("news")) {
            Map<Object, Object> contentMap = new HashMap<>();
            contentMap.put("title", remindInfoVo.getTitle());
            contentMap.put("description", content);
            contentMap.put("url", remindInfoVo.getUrl());
            contentMap.put("picurl", remindInfoVo.getPicture());
            ArrayList<Map<Object, Object>> articlesList = new ArrayList<>();
            articlesList.add(contentMap);
            Map<Object, Object> articles = new HashMap<>();
            articles.put("articles", articlesList);
            weChatData.put("news", articles);
        }

        return gson.toJson(weChatData);
    }

    public static String getToken(String corpId, String corpSecret) throws IOException {
        String resp = toAuth( "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=" + corpId + "&corpsecret=" + corpSecret);//拼接字符串得到url
        Map<String, Object> map = gson.fromJson(resp,
                new TypeToken<Map<String, Object>>() {
                }.getType());
        return map.get("access_token").toString();

    }

    protected static String toAuth(String Get_Token_Url) throws IOException {
        httpClient = HttpClients.createDefault();
        httpGet = new HttpGet(Get_Token_Url);
        CloseableHttpResponse response = httpClient.execute(httpGet);
        String resp;
        try {
            HttpEntity entity = response.getEntity();
            resp = EntityUtils.toString(entity, "utf-8");
            EntityUtils.consume(entity);
        } finally {
            response.close();
        }

        return resp;
    }

    private static String post(String charset, String contentType, String url, String data, String token) throws IOException {
        CloseableHttpClient httpclient = HttpClients.createDefault();
        httpPost = new HttpPost(url + token);
        httpPost.setHeader(CONTENT_TYPE, contentType);
        httpPost.setEntity(new StringEntity(data, charset));
        CloseableHttpResponse response = httpclient.execute(httpPost);
        String resp;
        try {
            HttpEntity entity = response.getEntity();
            resp = EntityUtils.toString(entity, charset);
            EntityUtils.consume(entity);
        } finally {
            response.close();
        }
        return resp;
    }
}
